<template>
  <a-card :bordered='false'>
    <!-- 查询区域 -->
    <div class='table-page-search-wrapper'>
      <a-form layout='inline' @keyup.enter.native='search'>
        <a-row :gutter='24'>
          <a-col :xl='6' :lg='7' :md='8' :sm='24'>
            <a-form-item label='入库单号'>
              <a-input placeholder='请输入入库单号' v-model='queryParams.no'></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl='6' :lg='7' :md='8' :sm='24'>
            <a-form-item label='入库人'>
              <a-input placeholder='请输入入库人' v-model='queryParams.inPersonName'></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl='6' :lg='7' :md='8' :sm='24'>
            <a-form-item label='冷库'>
              <a-select v-model='queryParams.storehouse' placeholder='请选择冷库'>
                <a-select-option v-for='d in storehouseList' :key='d.id' :value='d.code'>{{ d.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <template v-if='toggleSearchStatus'>
            <a-col :xl='6' :lg='7' :md='8' :sm='24'>
              <a-form-item label='入库时间'>
                <a-range-picker :style="{width: '100%'}"  format="YYYY-MM-DD"
                                :placeholder="['开始时间', '结束时间']"
                                v-model='rangePikerDate'
                                @change="onQueryDateChange" />
              </a-form-item>
            </a-col>

            <a-col :xl='6' :lg='7' :md='8' :sm='24'>
              <a-form-item label='状态'>
                <a-select v-model='queryParams.state' placeholder='请选择状态'>
                  <a-select-option v-for='(d,i) in stateList' :key='d.id' :value='d.id'>{{ d.value }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </template>
          <a-col :xl='6' :lg='7' :md='8' :sm='24'>
            <span style='float: left;overflow: hidden;' class='table-page-search-submitButtons'>
              <a-button type='primary' @click='search' icon='search'>查询</a-button>
              <a-button type='primary' @click='resetSearch' icon='reload' style='margin-left: 8px'>重置</a-button>
              <a @click='handleToggleSearch' style='margin-left: 8px'>
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class='table-operator'>
      <!--      <a-button @click='addModalShow' type='primary' icon='plus'>新增</a-button>-->
      <a-button type='primary' icon='download' @click="handleExportXls('采后物资入库主表')">导出</a-button>
      <!--      <a-upload name='file' :showUploadList='false' :multiple='false' :headers='tokenHeader' :action='importExcelUrl'
                      @change='handleImportExcel'>
              <a-button type='primary' icon='import'>导入</a-button>
            </a-upload>-->
      <!--      <a-dropdown v-if='selectedRowKeys.length > 0'>
              <a-menu slot='overlay'>
                <a-menu-item key='1' @click='materialDeleteBatch(selectedRowKeys)'>
                  <a-icon type='delete' />
                  删除
                </a-menu-item>
              </a-menu>
              <a-button style='margin-left: 8px'> 批量操作
                <a-icon type='down' />
              </a-button>
            </a-dropdown>-->
    </div>

    <!-- table区域-begin -->
    <div>
      <div class='ant-alert ant-alert-info' style='margin-bottom: 16px;'>
        <i class='anticon anticon-info-circle ant-alert-icon'></i> 已选择 <a
        style='font-weight: 600'>{{ selectedRowKeys.length }}</a>项
        <a style='margin-left: 24px' @click='onClearSelected'>清空</a>
      </div>

      <a-table
        ref='table'
        size='middle'
        bordered
        rowKey='id'
        class='j-table-force-nowrap'
        :columns='columns'
        :dataSource='mainDataSource'
        :pagination='mainPagination'
        :loading='loading'
        :scroll='{x:true}'
        :rowSelection='{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}'
        @change='mainPaginationChange'>

        <template slot='htmlSlot' slot-scope='text'>
          <div v-html='text'></div>
        </template>
        <template slot='imgSlot' slot-scope='text'>
          <span v-if='!text' style='font-size: 12px;font-style: italic;'>无图片</span>
          <img v-else :src='getImgView(text)' height='25px' alt=''
               style='max-width:80px;font-size: 12px;font-style: italic;' />
        </template>
        <template slot='fileSlot' slot-scope='text'>
          <span v-if='!text' style='font-size: 12px;font-style: italic;'>无文件</span>
          <a-button
            v-else
            :ghost='true'
            type='primary'
            icon='download'
            size='small'
            @click='uploadFile(text)'>
            下载
          </a-button>
        </template>

        <span slot='action' slot-scope='text, record'>
          <a-button type='primary' v-if='record.state===1' @click='editModalShow(record)'>财务确认</a-button>
          <a-button type='primary' v-if='record.state===2' @click='exportExcel(record)'>导出入库单</a-button><a-divider type='vertical' />
          <a-button type='danger' v-if='record.state===2' @click='editModalShow(record)'>撤销财务确认</a-button>
        </span>

      </a-table>
    </div>

    <!-- 第一弹窗   <flowerMaterialInMain-modal ref="modalForm" @ok="modalFormOk"></flowerMaterialInMain-modal>-->
    <a-modal v-model:visible='addOrEditVisible' width='80%' :title='firstModalTitle'
             :maskClosable='false'>
      <div>
        <a-row>
          <a-col :span='8'>
            <div style='display: inline-block'>单号：</div>
            <div style='display: inline-block;width: 60%'>
              <a-input v-model='material.no' placeholder='自动生成' style='width: 100%' disabled />
            </div>
          </a-col>
          <a-col :span='8'>
            <div style='display: inline-block;color: red;'>*</div>
            <div style='display: inline-block'>入库人：</div>
            <div style='display: inline-block;width: 60%'>
              <a-input disabled v-model='material.inPersonName' placeholder='请输入入库人' style='width: 100%' />
            </div>
          </a-col>

          <a-col :span='8'>
            <div style='display: inline-block;color: red;'>*</div>
            <div style='display: inline-block'>入库单名称：</div>
            <div style='display: inline-block;width: 60%'>
              <a-input disabled v-model='material.name' placeholder='请输入入库单名称' style='width: 100%' />
            </div>
          </a-col>
        </a-row>
        <a-row style='margin-top: 10px'>
          <a-col :span='8'>
            <div style='display: inline-block;color: red;'>*</div>
            <div style='display: inline-block'>入库时间：</div>
            <div disabled style='display: inline-block;width: 60%'>
              <a-date-picker disabled v-model:value='material.inTime'
                             :default-value='moment(defaultInTime, dateFormat)' :valueFormat='dateFormat'
                             placeholder='请选择出库时间' />
            </div>
          </a-col>
          <a-col :span='8'>
            <div style='display: inline-block;color: red;'>*</div>
            <div style='display: inline-block'>冷库：</div>
            <div style='display: inline-block;'>
              <a-select disabled v-model='material.storehouse' placeholder='请选择冷库' style='width: 200px;'>
                <a-select-option v-for='d in storehouseList' :key='d.id' :value='d.code'>{{ d.name }}</a-select-option>
              </a-select>
            </div>
          </a-col>
          <a-col :span='8'>
            <div style='display: inline-block;color: red;'>*</div>
            <div style='display: inline-block'>入库类型：</div>
            <div style='display: inline-block;'>
              <a-select disabled v-model='material.type' placeholder='请选择入库类型' style='width: 200px;'>
                <a-select-option v-for='d in materialTypeList' :key='d.text' :value='d.text'>{{ d.title }}
                </a-select-option>
              </a-select>
            </div>
          </a-col>
        </a-row>
        <a-row style='margin-top: 10px'>
          <a-col :span='8'>
            <div style='display: inline-block'>合同编号：</div>
            <div style='display: inline-block;width: 60%'>
              <a-input disabled v-model='material.contractNo' placeholder='请输入合同编号' style='width: 100%' />
            </div>
          </a-col>
          <a-col :span='8'>
            <div style='display: inline-block;color: red;'>*</div>
            <div style='display: inline-block;'>账期：</div>
            <div style='display: inline-block;'>
              <a-radio-group v-model='material.period' @change='periodChange' disabled>
                <a-radio v-for='(item,index) in periodList' :value='item'>{{ item}}</a-radio>
              </a-radio-group>
            </div>
          </a-col>
        </a-row>
        <a-row style='margin-top: 10px'>
          <a-col :span='24'>
            <div style='display: inline-block;width: 60px;'>备注：</div>
            <div style='display: inline-block;width: 85%'>
              <a-textarea disabled v-model='material.remarks' placeholder='请输入备注' />
            </div>
          </a-col>
        </a-row>
      </div>
      <a-divider />
      <div style='margin-top: -20px'>
        <div style='font-size: 20px;color: #0742f3;margin-bottom: 3px'>物资</div>
        <!--        <a-button style='display: inline-block' type='primary' icon='plus' @click='materialModalShow'>新增</a-button>-->
        <div style='display: inline-block;margin-left: 10px'>
          <span style='font-size: 14px;color: black;'>总价合计：</span><span
          style='color: red;margin-right: 20px'>{{ allTotalPrice }}</span>
          <span style='font-size: 14px;color: black;'>数量合计：</span><span style='color: red'>{{ allTotalNum }}</span>
        </div>
        <div style='margin-top: 7px'>
          <a-table :columns='materialColumns' :data-source='materialDataSource'
                   bordered row-key='uuid'
                   :loading='materialLoading'
                   :scroll='{ x: true, y: 300 }'
          >

<!--            <template v-for="colNum in ['num']" :slot='colNum' slot-scope='text, record, index'>
              <div :key='colNum' style='float: left;margin-right: 0;width: 100%;'>
                <input v-model:value='record.num' placeholder='请输入数量' style='width: 100%;'
                       @change='numberChange(record,record.num,record.price)' disabled/>
              </div>
            </template>-->

<!--            <template v-for="colTotalPrice in ['totalPrice']" :slot='colTotalPrice'
                      slot-scope='text, record, index'>
              <div :key='colTotalPrice' style='float: left;margin-right: 0;width: 100%;'>
                <input v-model:value='record.totalPrice'
                       placeholder='请输入总价'
                       style='width: 100%;'
                       @change='numberChange(record,record.num,record.totalPrice)' disabled/>
              </div>
            </template>-->
          </a-table>
        </div>
      </div>
      <!-- 操作按钮-->
      <template slot='footer'>
        <div style='display: inline-block;margin: 0px 10px'  >
          <a-popconfirm title='是否确认入库?' @confirm='() => materialAddOrEdit()'>
            <a-button type='primary' v-if='material.state===1'>财务确认</a-button>
          </a-popconfirm>
          <a-popconfirm title='是否确认撤销入库?' @confirm='() => financeSureBack()'>
            <a-button type='danger' v-if='material.state===2'>撤销财务确认</a-button>
          </a-popconfirm>
        </div>
      </template>
    </a-modal>

  </a-card>
</template>

<script>

import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import FlowerMaterialInMainModal from './modules/FlowerMaterialInMainModal'
import JDate from '@/components/jeecg/JDate.vue'
import '@/assets/less/TableExpand.less'
import { downFile } from '@/api/manage'
import {
  getFlowerMaterialCategorys,
  getFlowerMaterialCategorys1,
  getFlowerMaterialType,
  getFlowerMaterialInMain,
  getFlowerMaterialInfoByMainId,

  flowerMaterialInhouseSure,
  flowerMaterialInhouseSureBack,
  flowerMaterialInfinaSure,
  flowerMaterialInfinaSureBack,
  flowerMaterialInMainDelete,
  flowerMaterialInMainDeleteBatch,
  getFlowerStorehouseDict,
  period,
} from '@/api/api'
import moment from 'moment'
import { getTodayDate } from '../../utils/getDate'
import { getUuid } from '../../utils/uuid'
import { ifInteger, ifNumber,ifNumber1 } from '../../utils/ifNumber'

export default {
  name: 'FlowerMaterialInFinanceSure',
  mixins: [JeecgListMixin],
  components: {
    JDate,
    FlowerMaterialInMainModal
  },
  data() {
    return {
      description: '采后物资入库主表管理页面',
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '入库单号',
          align: 'center',
          dataIndex: 'no'
        }, {
          title:'账期',
          align:"center",
          width:100,
          dataIndex: 'period'
        },{
          title: '入库单名称',
          align: 'center',
          dataIndex: 'name'
        }, {
          title: '入库类型',
          align: 'center',
          dataIndex: 'type'
        },
        {
          title: '入库人',
          align: 'center',
          dataIndex: 'inPersonName'
        },
        {
          title: '入库时间',
          align: 'center',
          dataIndex: 'inTime',
          customRender: function(text) {
            return !text ? '' : (text.length > 10 ? text.substr(0, 10) : text)
          }
        },
        {
          title: '冷库',
          align: 'center',
          dataIndex: 'storehouse_dictText'
        }, {
          title: '合同编号',
          align: 'center',
          dataIndex: 'contractNo'
        }, {
          title: '库管确认人',
          align: 'center',
          dataIndex: 'houseSureUser'
        }, {
          title: '库管确认时间',
          align: 'center',
          dataIndex: 'houseSureTime'
        }, {
          title: '财务确认人',
          align: 'center',
          dataIndex: 'finaSureUser'
        }, {
          title: '财务确认时间',
          align: 'center',
          dataIndex: 'finaSureTime'
        },
        {
          title: '备注',
          align: 'center',
          dataIndex: 'remarks'
        },
        {
          title: '状态',
          align: 'center',
          dataIndex: 'state',
          customRender: function(text) {
            let stateString = ''
            switch (text) {
              case 0:
                stateString = '录入'
                break
              case 1:
                stateString = '财务确认'
                break
              case 2:
                stateString = '财务确认'
                break
              default:
                stateString = '未知'
            }
            return stateString
          }
        },
        {
          title: '创建人',
          align: 'center',
          dataIndex: 'createBy_dictText'
        },
        {
          title: '创建日期',
          align: 'center',
          dataIndex: 'createTime',
          customRender: function(text) {
            return !text ? '' : (text.length > 10 ? text.substr(0, 10) : text)
          }
        },

        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 120,
          scopedSlots: { customRender: 'action' }
        }
      ],
      url: {
        list: '/flowermater/flowerMaterialInMain/list',
        delete: '/flowermater/flowerMaterialInMain/delete',
        deleteBatch: '/flowermater/flowerMaterialInMain/deleteBatch',
        exportXlsUrl: '/flowermater/flowerMaterialInMain/exportXls',
        importExcelUrl: 'flowermater/flowerMaterialInMain/importExcel'
      },
      dictOptions: {},
      mainDataSource: [],//主页面中的数据源
      addOrEditVisible: false,//是否打开新增或编辑的弹窗
      selectMaterialVisible: false,//是否打开物资选择的弹窗
      firstModalTitle: '',//第一个弹窗中的标题
      addOrEditFlag: 'add',//打开的弹窗是新增还是编辑的标识
      material: {//第一个弹窗中的主表数据
        period:'',//账期
        inPersonName: '',//入库人
        name: '',//入库单名称
        inTime: '',//入库时间
        storehouse: '',//冷库
        type: '',//入库类型
        contractNo: '',//
        houseSureUser: '',//
        houseSureTime: '',//
        finaSureUser: '',//
        finaSureTime: '',//
        remarks: ''//备注
      },
      storehouseList: [],//冷库列表
      materialTypeList: [],//入库类型列表
      defaultInTime: '',
      dateFormat: 'YYYY-MM-DD',
      materialColumns: [// 第一个弹窗中表格的表头
        {
          title: '供应商选择',
          width: 140,
          scopedSlots: { customRender: 'supplier' }
        }, {
          title: '供应商',
          dataIndex: 'supplier',
          align: 'center',
          width: 130
        }, {
          title: '物资名称',
          dataIndex: 'name',
          align: 'center',
          width: 130
        },
        {
          title: '物资编码',
          dataIndex: 'code',
          align: 'center',
          width: 130
        }, {
          title: '规格',
          dataIndex: 'specs',
          align: 'center',
          width: 130
        }, {
          title: '型号',
          dataIndex: 'modelname',
          align: 'center',
          width: 130
        }, {
          title: '入库单位',
          dataIndex: 'unit',
          align: 'center',
          width: 90
        }, {
          title: '计量单位',
          dataIndex: 'unitMeasure',
          align: 'center',
          width: 90
        }, {
          title: '数量',
          dataIndex: 'num',
          align: 'center',
          width: 140,
          scopedSlots: { customRender: 'num' }
        }, {
          title: '单价',
          dataIndex: 'price',
          align: 'center',
          width: 140,
          scopedSlots: { customRender: 'price' }
        }, {
          title: '总价',
          dataIndex: 'totalPrice',
          align: 'center',
          width: 140,
          scopedSlots: { customRender: 'totalPrice' }
        },
        {
          title: '操作',
          dataIndex: 'operation',
          align: 'center',
          width: 100,
          fixed: 'right',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      materialDataSource: [],//第一个弹窗中的数据源
      allTotalPrice: 0,//第一个弹窗中所有商品的总价
      allTotalNum: 0,//第一个弹窗中所有商品的总数量
      selectMaterialColumns: [// 第二个弹窗中表格的表头
        {
          title: '物资名称',
          dataIndex: 'name',
          align: 'center'
        },
        {
          title: '物资编码',
          dataIndex: 'code',
          align: 'center'
        }, {
          title: '规格',
          dataIndex: 'specs',
          align: 'center'
        }, {
          title: '型号',
          dataIndex: 'modelname',
          align: 'center'
        }, {
          title: '入库单位',
          dataIndex: 'unit',
          align: 'center'
        }, {
          title: '计量单位',
          dataIndex: 'unitMeasure',
          align: 'center'
        }
      ],
      materialCategorysFlag: true,//选中编辑的入库单是否已经有物资，true为是，false为否
      mainPagination: {// 主页表格的分页
        total: 0,
        current: 1,
        pageSize: 10,//每页中显示10条数据
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],//每页中显示的数据
        showTotal: total => `共有 ${total} 条数据`  //分页中显示总的数据
      },
      selectMaterialPagination: {//选择物资弹窗中表格的分页
        total: 0,
        current: 1,
        pageSize: 5,//每页中显示5条数据
        showSizeChanger: true,
        pageSizeOptions: ['5', '10', '15', '20'],//每页中显示的数据
        showTotal: total => `共有 ${total} 条数据`  //分页中显示总的数据
      },
      selectMaterialDataSource: [],//第二个弹窗中的数据源
      selectMaterialCategorys: [],//第二个弹窗中已选择的物资
      materialLoading: false,//是否显示第一个弹窗中表格的加载状态
      selectMaterialLoading: false,//是否显示第二个弹窗中表格的加载状态
      queryParams: {// 主页查询
        no: '',//入库单号
        inPersonName: '',//入库人
        storehouse: '',//冷库
        state: '',//状态
        sDate:'',//开始时间
        eDate:'',//结束时间
      },
      rangePikerDate:[],
      stateList: [{ id: 0, value: '录入' }, { id: 1, value: '库管确认' }, { id: 2, value: '财务确认' }],
      queryMaterialCategorysParams: {// 物资选择弹窗的查询
        name: '',// 物资名称
        code: ''// 物资编码
      },
      periodList:[],//从后台取回的账期列表（上个账期，当前账期，下个账期）
    }
  },
  computed: {
    importExcelUrl: function() {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    }
  },
  created() {
    //获取冷库列表
    this.storehouseList = JSON.parse(localStorage.getItem('ch_storehouse') ? localStorage.getItem('ch_storehouse') : '')
    this.getPeriod()
  },
  mounted() {
    this.todayDate()
    this.queryMaterialInMain()
    this.queryMaterialType()
    //this.queryFlowerStorehouseDict()
  },
  methods: {
    moment,
    initDictConfig() {
    },
    search() {// 主页中根据条件查询
      this.mainPagination.current=1
      this.queryMaterialInMain()
    },
    onQueryDateChange(date, dateString){// 日期段选择改变时的回调
      this.queryParams.sDate = dateString[0]
      this.queryParams.eDate = dateString[1]
    },
    resetSearch() {// 重置查询
      this.queryParams = {// 主页查询
        no: '',//入库单号
        inPersonName: '',//入库人
        storehouse: '',//冷库
        state: '',//状态
        sDate:'',//开始时间
        eDate:'',//结束时间
      }
      this.rangePikerDate=[]
      this.search()
    },
    searchMaterialCategorys() {// 物资选择弹窗中的物资
      this.selectMaterialPagination.current=1
      this.queryFlowerMaterialCategorys()
    },
    queryMaterialInMain() {//获取物资入库单数据
      this.loading = true
      this.materialDataSource.length = 0
      let params = {
        pageNo: this.mainPagination.current,
        pageSize: this.mainPagination.pageSize
      }
      params={...this.queryParams,...params}
      getFlowerMaterialInMain(params).then(res => {
        if (res.success) {
          this.mainPagination.total = res.result.total
          this.mainDataSource = res.result.records
        } else {
          this.$message.error(res.message)
        }
        this.loading = false
      })
    },

    mainPaginationChange(pagination) {
      this.mainPagination.current = pagination.current
      this.mainPagination.pageSize = pagination.pageSize
      this.queryMaterialInMain()
    },
    addModalShow() {//打开第一个弹窗(新增)
      this.addOrEditFlag = 'add'
      this.firstModalTitle = '新增'
      this.material = {//第一个弹窗中的主表数据
        period:'',//账期
        inPersonName: '',//入库人
        name: '',//入库单名称
        inTime: '',//入库时间
        storehouse: '',//冷库
        type: '',//入库类型
        contractNo: '',//合同编号
        remarks: ''//备注
      },
        this.todayDate()
      this.allTotalPrice = 0
      this.allTotalNum = 0
      this.materialDataSource = []
      this.addOrEditVisible = !this.addOrEditVisible
    },
    editModalShow(record) {//打开第一个弹窗(编辑)
      this.addOrEditFlag = 'edit'
      this.firstModalTitle = '编辑'
      this.material = record
      this.selectMaterialDataSource.length = 0
      this.allTotalPrice = 0
      this.allTotalNum = 0
      this.queryFlowerMaterialDetailByMainId(record.id)
      this.addOrEditVisible = !this.addOrEditVisible
    },
    materialModalShow() {//打开第二个弹窗
      /*设置下面这两行是为了处理再次打开商品选择弹窗时，
      还会在界面上保留上次选择物资而实际上没有选择任何物资的问题*/
      this.selectedRowKeys.length = 0
      this.selectionRows.length = 0

      this.selectMaterialPagination = {//选择物资弹窗中表格的分页
        total: 0,
        current: 1,
        pageSize: 5,//每页中显示5条数据
        showSizeChanger: true,
        pageSizeOptions: ['5', '10', '15', '20'],//每页中显示的数据
        showTotal: total => `共有 ${total} 条数据`  //分页中显示总的数据
      }
      this.queryFlowerMaterialCategorys()
      this.selectMaterialVisible = !this.selectMaterialVisible
    },
    queryFlowerMaterialDetailByMainId(id) {//获取第一个弹窗中的物资信息
      this.materialLoading = true
      let params = {
        id: id
      }
      getFlowerMaterialInfoByMainId(params).then(res => {
        if (res.success) {
          this.materialDataSource = res.result

          this.materialDataSource.map(item => {
            item.uuid = getUuid()
          })

          if (this.materialDataSource.length > 0) {
            this.materialCategorysFlag = true
          } else {
            this.materialCategorysFlag = false
          }

          for (let item of this.materialDataSource) {
            this.allTotalPrice += item.totalPrice * 10 / 10// 计算总价合计
            this.allTotalNum += item.num * 10 / 10// 计算数量合计
          }
          // 保留两位小数
          this.allTotalPrice = (this.allTotalPrice * 10 / 10).toFixed(2)
        } else {
          this.$message.error(res.message)
        }
        this.materialLoading = false
      })
    },
    queryFlowerMaterialCategorys() {//获取第二个弹窗中的物资类型
      this.selectMaterialLoading = true

      let params = {
        pageNo: this.selectMaterialPagination.current,
        pageSize: this.selectMaterialPagination.pageSize
      }
      params={...this.queryMaterialCategorysParams,...params}
      getFlowerMaterialCategorys(params).then(res => {
        if (res.success) {
          this.selectMaterialPagination.total = res.result.total
          this.selectMaterialDataSource = res.result.records

          this.selectMaterialDataSource.map(item => {
            //将uuid封装进selectMaterialDataSource中的各物资对象中,为第一个弹窗table中的key使用
            item.uuid = getUuid()
            item.num = ''//封装进num
            item.price = ''//封装进price
            item.totalPrice = ''//封装进totalPrice
          })
        } else {
          this.$message.error(res.message)
        }
        this.selectMaterialLoading = false
      })
    },

    onMaterialCategorysSelectChange(selectedRowKeys, selectionRows) {//第二个弹窗中选择物资时的回调
      this.selectedRowKeys = selectedRowKeys// 如果不加这两行的话无法多选
      this.selectionRows = selectionRows

      this.selectMaterialCategorys = selectionRows
    },
    materialCategorysAdd() {// 第二个弹窗中的确定选择物资
      let haveMaterialFlag = false//第一个弹窗中是否已包含所选择物资的标识
      for (let item1 of this.materialDataSource) {
        for (let item2 of this.selectMaterialCategorys) {
          if (item2.code === item1.code) {
            this.$message.error(`该入库物资单中已有物资编码为:${item1.code}的物资`)
            haveMaterialFlag = true
            return
          }
        }
      }
      if (!haveMaterialFlag) {
        this.materialDataSource = [...this.materialDataSource, ...this.selectMaterialCategorys]
      }
      this.selectMaterialVisible = !this.selectMaterialVisible
    },
    selectMaterialPaginationChange(pagination) {
      this.selectMaterialPagination.current = pagination.current
      this.selectMaterialPagination.pageSize = pagination.pageSize
      this.queryFlowerMaterialCategorys()
    },
    materialAddOrEdit() {// 确定新增或编辑物资
      //财务确认
      let allNumberFlag = true//是否所有的商品都有数量的标识
      let allTotalPriceFlag = true//是否所有的商品都有总价的标识
      if (this.material.inPersonName === '') {
        this.$message.error('请输入入库人')
      } /*else if (this.material.inPersonCode === '') {
        this.$message.error('请输入入库人编码')
      }*/ else if (this.material.name === '') {
        this.$message.error('请输入入库单名称')
      } else if (this.material.inTime === '') {
        this.$message.error('请选择入库时间')
      } else if (this.material.storehouse === '') {
        this.$message.error('请选择冷库')
      } else if (this.material.type === '') {
        this.$message.error('请选择入库类型')
      } else if (this.materialDataSource.length === 0) {
        this.$message.error('至少需要有一个入库物资')
      } else {
        for (let item of this.materialDataSource) {

          if (item.num === '' || item.num === null) {
            this.$message.error('请输入数量')
            allNumberFlag = false
            return
          }
          if (!ifNumber1(item.num)) {
            this.$message.error('数量必须为数字')
            allNumberFlag = false
            return
          }
          if (item.totalPrice === '' || item.totalPrice === null) {
            this.$message.error('请输入总价')
            allTotalPriceFlag = false
            return
          }
          if (!ifNumber1(item.totalPrice)) {
            this.$message.error('总价必须为数字')
            allTotalPriceFlag = false
            return
          }
          if (!item.supplier) {
            this.$message.error('请选择供应商')
            allTotalPriceFlag = false
            return
          }
        }
        this.material.flowerMaterialInList = this.materialDataSource//将物资信息封装进material中
        if( this.material.finaSureUser){
          this.$message.success("财务已经确认过了")
        }
        flowerMaterialInfinaSure(this.material).then(res => {
          if (res.success) {
            this.queryMaterialInMain()
            this.$message.success(res.message)
          } else {
            this.$message.error(res.message)
          }
          this.addOrEditVisible = false
        })

    }
  },
  materialDelete(id) {
    flowerMaterialInMainDelete({ id: id }).then(res => {
      if (res.success) {
        this.queryMaterialInMain()
        this.$message.success('删除成功')
      } else {
        this.$message.error(res.message)
      }
    })
  },
  materialDeleteBatch(selectedRowKeys) {
    if (selectedRowKeys.length > 0) {
      let ids = ''
      for (let item of selectedRowKeys) {
        ids = ids + item + ','
      }
      flowerMaterialInMainDeleteBatch({ ids: ids }).then(res => {
        if (res.success) {
          this.queryMaterialInMain()
          this.selectedRowKeys.length = 0
          this.$message.success('批量删除成功')
        } else {
          this.$message.error(res.message)
        }
      })
    }
  },
    materialCategorysDelete(id) {
      const dataSource = [...this.materialDataSource]
      this.materialDataSource = dataSource.filter(item => item.uuid !== id)

      // 计算出合计总价、合计数量
      this.allTotalPrice = 0
      this.allTotalNum = 0
      for (let item of this.materialDataSource) {
        if (ifNumber1(item.totalPrice) && ifNumber1(item.num)) {
          this.allTotalPrice += item.totalPrice * 10 / 10
          this.allTotalNum += item.num * 10 / 10
        } else {
          this.allTotalPrice = null
          this.allTotalNum = null
          return
        }
      }
      // 保留两位小数
      this.allTotalPrice = (this.allTotalPrice * 10 / 10).toFixed(2)
    },
  //查询入库类型
  queryMaterialType() {
    getFlowerMaterialType().then((res) => {
      if (res.success) {
        this.materialTypeList = res.result
      }
    })
  },
  todayDate() {// 设置新增弹窗中的入库时间的默认值为当前日期
    this.defaultInTime = getTodayDate()
    this.material.inTime = getTodayDate()
  },
  /*queryFlowerStorehouseDict() {//获取冷库
    getFlowerStorehouseDict().then(res => {
      if (res.success) {
        this.storehouseList = res.result
      } else {
        this.$message.error(res.message)
      }
    })
  },*/
    numberChange(record, number, totalPrice) {
      if (ifNumber1(number) && (number !== null || number !== '') && ifNumber1(totalPrice) && (totalPrice !== null || totalPrice !== '')) {
        if (number === 0 || number === '0') {
          record.price = 0
        }else {
          let price = (totalPrice * 10 / 10) / (number * 10 / 10)
          record.price = price.toFixed(2)
        }
      } else {
        record.price = null
      }

      // 计算出合计总价、合计数量
      this.allTotalPrice = 0
      this.allTotalNum = 0
      for (let item of this.materialDataSource) {
        if (ifNumber1(item.totalPrice) && ifNumber1(item.num)) {
          this.allTotalPrice += item.totalPrice * 10 / 10
          this.allTotalNum += item.num * 10 / 10
        } else {
          this.allTotalPrice = null
          this.allTotalNum = null
          return
        }
      }
      // 保留两位小数
      this.allTotalPrice = (this.allTotalPrice * 10 / 10).toFixed(2)
    },
    financeSureBack(){
      if( !this.material.houseSureUser){
        this.$message.success("还未进行财务确认")
      }
      flowerMaterialInfinaSureBack(this.material).then(res => {
        if (res.success) {
          this.queryMaterialInMain()
          this.$message.success(res.message)
        } else {
          this.$message.error(res.message)
        }
        this.addOrEditVisible = false
      })
    },
    exportExcel(record){
      let  dt = new Date()
      let fileName = '采后物资入库单'+ record.no +"-"+ dt.getFullYear()+"-"+(dt.getMonth()+1)+"-"+dt.getDate()

      let urlss = '/flowermater/flowerMaterialInMain/exportXlsForTemp'
      downFile(urlss, {id:record.id } ).then((data) => {
        if (!data) {
          this.$message.warning('文件下载失败')
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xlsx')
        } else {
          let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xlsx')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
      })
    },
    getPeriod() {
      period().then(res => {
        this.periodList = res
      })
    },
    //账期单选的change
    periodChange(e) {
      this.material.period = e.target.value
    }
}
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>